//
//  HomeMainController.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/6.
//

import UIKit
import JFPopup
import SnapKit
import Reusable
import GKCover
import WebKit
import IQKeyboardManagerSwift
import FinAuthLiveV5Detect

class HomeMainController: BaseWebViewController {
    
    private lazy var testButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage("t_0".toImage, for: .normal)
        button.setImage("t_0".toImage, for: .highlighted)
        button.addTarget(self, action: #selector(testAction), for: .touchUpInside)
        return button
    }()
    
    /// 翻译列表
    lazy var translationListView: TranslationListView = {
        let view = TranslationListView.loadFromNib()
        view.didSelectedTranslationBlock = { [weak self] model in
            if let model = model {
                xLog("邀请翻译加入通话 \(model.name)")
                // 要弱引用，容易循环引用，无法销毁
            }
            GKCover.hide()
        }
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initNav()
        initUI()
#if DEBUG
        initTest()
#else
#endif
    }
    
    //    override func viewDidAppear(_ animated: Bool) {
    //        super.viewDidAppear(animated)
    //        onNativeShow(className)
    //    }
    //
    //    override func viewDidDisappear(_ animated: Bool) {
    //        super.viewDidDisappear(animated)
    //        onNativeHide(className)
    //    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.isEnabled = false
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.isEnabled = true
    }
}

private extension HomeMainController {
    func initNav() {
        vhl_navBarHide = true
        navigationItem.leftBarButtonItem = nil
    }
    
    func initUI() {
        let url = H5UrlManager.homeH5Url
        xLog("首页 url：\(url)")
        let request = URLRequest(url: URL(string: url)!)
        wkWebView.load(request)
        wkWebView.snp.remakeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalToSuperview().offset(-xIphoneTabBarSafeHeight)
        }
        
        AUAssistiveTouch.addTouchView(on: self.view)
        AUAssistiveTouch.shared.maxArea = CGRect(x: 0, y: 100, width: xScreenW, height: xScreenH - 100 - 80)
        AUAssistiveTouch.shared.clickClosure = {
            xLog("点击事件")
            let portalView = TranslationPortalView.loadFromNib()
            portalView.closeBlock = {
                self.popup.dismissPopup()
            }
            portalView.didSelectedItemBlock = { type in
                self.popup.dismissPopup()
                switch type {
                case .realtime:  // 同声传译
                    self.push(RealtimeTranslatorController())
                    
                case .picture:  // 图片翻译
                    self.push(TranslationPictureController())
                    
                case .audio:  // 语音翻译
                    self.push(TranslationAudioController())
                    
                case .word:  // 文字翻译
                    self.push(TranslatorWordController())
                }
                
            }
            
            self.popup.dialog {
                portalView
            }
        }
        AUAssistiveTouch.setLocation(with: CGPoint(x: xScreenW, y: 100))
    }
}

extension HomeMainController {
    
    func initTest() {
        // 课程表
        view.addSubview(testButton)
        testButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-16)
            make.bottom.equalToSuperview().offset(-xIphoneTabBarSafeHeight - 24)
            make.width.height.equalTo(40)
        }
    }
    
    @objc func testAction() {
        YLAlert(
            controller: self,
            style: .actionSheet,
            title: "功能测试",
            actionTitles: [
                "0.中文",
                "1.俄语",
                "2.视频通话",
                "3.IM Chat",
                "4.活体认证",
                "5.文字翻译",
                "6.原生文字翻译",
                "7.原生文字翻译"
            ]
        ) { [self] action, index in
            
            if index == 0 {
                LanguageManager.setLanguage(.zh)
                
            } else if index == 1 {
                LanguageManager.setLanguage(.ru)
                
            } else if index == 2 {
                let alertController = UIAlertController(title: "视频通话", message: nil)
                alertController.addTextField { textField in
                    textField.placeholder = "输入用户 id"
                    textField.keyboardType = .numberPad
                }
                let cancelAction = UIAlertAction(title: "取消", style: .cancel) { action in }
                let sureAction = UIAlertAction(title: "确定", style: .default) { action in
                    if let textField = alertController.textFields?.first {
                        YLHUD.showLottie()
                        
                        MineMainViewModel.loadUserInfo(textField.text!) { userModel in
                            if let model = userModel {
                                YLHUD.hideHUD()
                                if model.identityType == .interpreter {
                                    self.videoCall(userId: String(model.id), userName: model.username, avatar: model.avatar, isTranslation: false)
                                    return
                                }
                                
                                let isTranslation = !LanguageManager.isSameLanguage(UserProfile.country, model.country)
                                self.videoCall(userId: String(model.id), userName: model.username, avatar: model.avatar, isTranslation: isTranslation)
                            }
                        }
                        
                    }
                }
                alertController.addAction(cancelAction)
                alertController.addAction(sureAction)
                present(alertController, animated: true, completion: nil)
                
            } else if index == 3 {
                let alertController = UIAlertController(title: "IM Chat", message: nil)
                alertController.addTextField { textField in
                    textField.placeholder = "输入用户 id"
                    textField.keyboardType = .numberPad
                }
                let cancelAction = UIAlertAction(title: "取消", style: .cancel) { action in }
                let sureAction = UIAlertAction(title: "确定", style: .default) { action in
                    if let textField = alertController.textFields?.first {
                        self.im(textField.text!)
                    }
                }
                alertController.addAction(cancelAction)
                alertController.addAction(sureAction)
                present(alertController, animated: true, completion: nil)
                
            } else if index == 4 {
                
            } else if index == 5 {
                
            } else if index == 6 {
                
            } else if index == 7 {
                
            } else if index == 8 {
                
            }
        }
    }
    
    func uploadImage(_ image: UIImage) {
        YLHUD.showLottie()
        let object = AliOSSObject.init(image)
        AliOSSUtil.shared.uploadSingleObject(object) { bytesSent, totalBytesSent, totalBytesExpectedToSend in
            let progress = Double(totalBytesSent) / Double(totalBytesExpectedToSend)
            xLog("[上传] 图片上传进度 \(Int(progress*100))")
        } completion: { object, error in
            DispatchQueue.main.async {
                YLHUD.hideHUD()
                if error != nil {
                    YLHUD.showHint(.error, "上传失败")
                    xLog(error)
                    return
                }
                xLog(object.url)
            }
        }
    }
    
    func im(_ id: String) {
        push(ZIMKitMessagesListVC(conversationID: id, type: .peer, conversationName: ""))
        // push(ZIMKitMessagesListVC(conversationID: "#A7TLxhI88", type: .group, conversationName: ""))
    }
    
    func live() {
        
        let appID = KeyCenter.IM.appID
        let appSign = KeyCenter.IM.appSign
        let userName = UserProfile.username
        let userId = String(UserProfile.userId)
        let liveId = "live_\(userId)_\(Date.sg.timestamp())"
        
        let config: ZegoUIKitPrebuiltLiveStreamingConfig = ZegoUIKitPrebuiltLiveStreamingConfig.host(enableSignalingPlugin: true)
        // 修改语言为中文
        config.translationText = ZegoLiveTranslationText(language: LanguageManager.isCountryCN ? .CHS: .RU)
        config.enableCoHosting = true
        
        let liveVC = ZegoUIKitPrebuiltLiveStreamingVC(
            appID,
            appSign: appSign,
            userID: userId,
            userName: userName,
            liveID: liveId,
            config: config
        )
        liveVC.modalPresentationStyle = .fullScreen
        present(liveVC)
    }
    
    // 观众观看直播
    func watchLive(_ sender: Any) {
        
        let appID = KeyCenter.IM.appID
        let appSign = KeyCenter.IM.appSign
        let userName = UserProfile.username
        let userId = String(UserProfile.userId)
        let liveId = "live_\(userId)_\(Date.sg.timestamp())"
        
        let config: ZegoUIKitPrebuiltLiveStreamingConfig = ZegoUIKitPrebuiltLiveStreamingConfig.audience(enableSignalingPlugin: true)
        // 修改语言为中文
        config.translationText = ZegoLiveTranslationText(language: LanguageManager.isCountryCN ? .CHS: .RU)
        config.enableCoHosting = true
        
        let liveVC: ZegoUIKitPrebuiltLiveStreamingVC = ZegoUIKitPrebuiltLiveStreamingVC(
            appID,
            appSign: appSign,
            userID: userId,
            userName: userName,
            liveID: liveId,
            config: config
        )
        liveVC.modalPresentationStyle = .fullScreen
        self.present(liveVC, animated: true, completion: nil)
    }
    
}
